package org.example.demo02;

import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.web.bind.annotation.*;

import java.io.StringReader;

@RestController
@RequestMapping("/header")
public class HeaderController {
    //获取cookie
    @RequestMapping("/getCookie")
    public String getCookie(HttpServletRequest request) {
        Cookie[] cookies = request.getCookies();
        //可能为空可以做空指针处理
        for (Cookie cookie : cookies) {
            System.out.println(cookie.getName() + ":" + cookie.getValue());
        }
        return "获取cookie成功";
    }
    @RequestMapping("/getCookie2")
    public String getCookie2(@CookieValue("bite") String bite) {
        return "从Cookie中获取信息，bite：" + bite;
    }
    @RequestMapping("/setSession")
    public String setSession(HttpServletRequest request) {
        //设置  Session对象
        HttpSession session = request.getSession();
        session.setAttribute("userName","moyipeng");
        session.setAttribute("age",20);
        session.setAttribute("bigName","curry");
        return "设置session成功";
    }
    @RequestMapping("/getSession")
    public String getSession(HttpServletRequest request) {
        HttpSession session = request.getSession();
        //获取
        String userName =(String) session.getAttribute("userName");
        System.out.println(session.getAttribute("age"));
        return "从session中获取信息，userName：" + userName;
    }
    @RequestMapping("/getSession2")
    public String getSession2(HttpSession session) {
        String userName = (String) session.getAttribute("userName");
        System.out.println(session.getAttribute("age"));
        return "从session2中获取信息，userName:" + userName;
    }
    @RequestMapping("/getSession3")
    public String getSession3 (@SessionAttribute("bigName") String userName) {
        return "从session3中获取信息，bigName：" + userName;
    }
@RequestMapping("/getHeader")
    public String getHeader(HttpServletRequest request) {
        String userAgent = request.getHeader("User-Agent");
        return "userAgent:" + userAgent;
    }
    @RequestMapping("/getHeader2")
    public String getHeader2(@RequestHeader("User-Agent") String userAgent) {
        return "userAgent:" + userAgent;
    }
}
